import express from 'express';
import { LangChainService } from '../services/langchainService';
import { authenticateToken } from '../middleware/auth';

// 创建LangChain服务实例
const langchainService = new LangChainService();

const router = express.Router();

// 所有LangChain聊天路由需要认证
router.use(authenticateToken);

// 系统提示词
const SYSTEM_PROMPT = `你是AIDE智能任务管理助手。你可以帮助用户创建、更新、查询和管理任务。

你可以使用以下功能：
- 创建新任务 (create_task)
- 更新现有任务 (update_task)
- 查询任务列表 (query_tasks)
- 标记任务完成 (complete_task)
- 删除任务 (delete_task)
- 获取任务统计 (get_task_stats)

请根据用户需求提供帮助，如果需要操作任务，请使用相应的功能。回答要简洁明了，并且要友好和有用。`;

// 流式聊天接口
router.post('/stream', async (req, res) => {
  try {
    console.log('[LangChain Route] 🚀 收到流式聊天请求');
    console.log('[LangChain Route] 📥 请求体:', JSON.stringify(req.body, null, 2));
    
    const { messages, messageId } = req.body;
    const userId = (req as any).userId; // 从认证中间件获取用户ID
    
    console.log(`[LangChain Route] 👤 用户ID: ${userId}`);

    // 设置SSE响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    // 生成消息ID
    const currentMessageId = messageId || Date.now().toString();
    console.log(`[LangChain Route] 🆔 消息ID: ${currentMessageId}`);

    // 构建消息数组，包含系统提示词
    const allMessages = [
      { role: 'system', content: SYSTEM_PROMPT },
      ...messages
    ];
    
    console.log('[LangChain Route] 📝 完整消息数组:', JSON.stringify(allMessages, null, 2));

    // 客户端连接状态
    let isClientConnected = true;

    // 安全写入函数
    const safeWrite = (data: any) => {
      if (!res.destroyed) {
        try {
          res.write(`data: ${JSON.stringify(data)}\n\n`);
          console.log(`[LangChain Route] 📤 发送数据:`, JSON.stringify(data, null, 2));
        } catch (error) {
          console.error('[LangChain] 写入响应失败:', error);
          isClientConnected = false;
        }
      } else {
        console.log(`[LangChain Route] ⚠️ 响应已销毁，无法写入数据`);
      }
    };


    // 创建AbortController用于中断流式响应
    const abortController = new AbortController();
    
    // 当客户端断开连接时，中断流式响应
    req.on('close', () => {
      console.log(`[LangChain] 客户端断开连接，中断流式响应: ${currentMessageId}`);
      abortController.abort();
    });
    
    req.on('timeout', () => {
      console.log(`[LangChain] 请求超时，中断流式响应: ${currentMessageId}`);
      abortController.abort();
    });
    
    req.on('error', (error) => {
      console.log(`[LangChain] 客户端错误，中断流式响应: ${currentMessageId}`, error.message);
      abortController.abort();
    });

    // 开始流式处理
    console.log('[LangChain Route] 🔄 开始调用LangChain服务...');
    try {
      for await (const chunk of langchainService.streamChat(allMessages, userId, abortController.signal)) {
        // 检查客户端是否已断开连接
        if (!isClientConnected) {
          console.log(`[LangChain Route] ⚠️ 客户端已断开连接，停止处理流式响应`);
          break;
        }
        
        console.log(`[LangChain Route] 📦 收到chunk:`, JSON.stringify(chunk, null, 2));

        switch (chunk.type) {
          case 'content':
            console.log(`[LangChain Route] 📝 内容增量: "${chunk.content}"`);
            safeWrite({ 
              delta: chunk.content, 
              messageId: currentMessageId 
            });
            break;

          case 'tool_call':
            console.log(`[LangChain Route] 🔧 工具调用:`, JSON.stringify(chunk.toolCall, null, 2));
            safeWrite({ 
              functionCall: chunk.toolCall, 
              messageId: currentMessageId 
            });
            break;

          case 'tool_result':
            console.log(`[LangChain Route] ✅ 工具结果:`, JSON.stringify(chunk.toolResult, null, 2));
            try {
              const parsedResult = JSON.parse(chunk.toolResult.result);
              safeWrite({ 
                functionResult: {
                  name: chunk.toolResult.name,
                  result: parsedResult,
                  message: `成功执行函数：${chunk.toolResult.name}`
                }, 
                messageId: currentMessageId 
              });
            } catch (parseError) {
              console.error(`[LangChain Route] ❌ 解析工具结果失败:`, parseError);
              safeWrite({ 
                functionResult: {
                  name: chunk.toolResult.name,
                  result: chunk.toolResult.result,
                  message: `成功执行函数：${chunk.toolResult.name}`
                }, 
                messageId: currentMessageId 
              });
            }
            break;

          case 'tool_error':
            console.error(`[LangChain Route] ❌ 工具错误:`, JSON.stringify(chunk.toolError, null, 2));
            safeWrite({ 
              functionError: {
                name: chunk.toolError.name,
                error: chunk.toolError.error
              }, 
              messageId: currentMessageId 
            });
            break;

          case 'error':
            console.error(`[LangChain Route] ❌ 聊天错误:`, chunk.error);
            safeWrite({ 
              error: chunk.error, 
              messageId: currentMessageId 
            });
            break;
        }
      }

      // 发送完成标记 - 无论客户端是否连接都要发送
      safeWrite({ 
        final: true, 
        messageId: currentMessageId 
      });
      console.log(`[${currentMessageId}] 流式响应完成`);
      
      // 关闭连接
      if (!res.destroyed) {
        res.end();
        console.log(`[${currentMessageId}] 连接已关闭`);
      }

    } catch (streamError) {
      console.error(`[${currentMessageId}] 流式处理错误:`, streamError);
      safeWrite({ 
        error: streamError instanceof Error ? streamError.message : '流式处理失败',
        messageId: currentMessageId 
      });
      safeWrite({ 
        final: true, 
        messageId: currentMessageId 
      });
      
      // 关闭连接
      if (!res.destroyed) {
        res.end();
        console.log(`[${currentMessageId}] 错误后连接已关闭`);
      }
    }

  } catch (error) {
    console.error('[LangChain] 聊天路由错误:', error);
    
    if (!res.headersSent) {
      res.status(500).json({
        error: error instanceof Error ? error.message : '聊天服务错误'
      });
    }
  }
});

// 非流式聊天接口（用于测试）
router.post('/chat', async (req, res) => {
  try {
    const { messages } = req.body;
    const userId = (req as any).userId; // 从认证中间件获取用户ID

    // 构建消息数组，包含系统提示词
    const allMessages = [
      { role: 'system', content: SYSTEM_PROMPT },
      ...messages
    ];

    const response = await langchainService.chat(allMessages, userId);
    
    res.json({
      success: true,
      data: response
    });

  } catch (error) {
    console.error('[LangChain] 聊天错误:', error);
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : '聊天失败'
    });
  }
});

// 健康检查接口
router.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'LangChain聊天服务运行正常',
    timestamp: new Date().toISOString()
  });
});

export default router;
